package fr.epita.mti
{

	// ActionScript file
	import flash.events.EventDispatcher;
	import flash.events.FileListEvent;
	import flash.filesystem.File;
	import flash.utils.setTimeout;
	
	import fr.epita.mti.event.OnzheurEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.messaging.channels.StreamingAMFChannel;
	
	public class Scan extends EventDispatcher
	{		
		private var currentNodes:Array = []; // The nodes (files and directories) in the current directory
		private var directoryStack:Array = []; // An array of directories (File objects) to search.
		private var currentSubdirectories:Array; // An array of directories in the current directory.
		private var nodeCount:uint = 0; // The number of files and directories searched.
		[Bindable]
		private var resultData:ArrayCollection = new ArrayCollection(); 
		// A collection of object with data pertaining to matching files
		private var pattern:RegExp; // The pattern to search for in file (and directory) names
		//private var defaultFolderPath:String =File.userDirectory.nativePath;
		
		public function Scan()
		{
		}

		/**
		 * Getter
		 */
		public function getResultData():ArrayCollection
		{
			return resultData;	
		}
			
			
		/**
		 * Called when the application UI is rendered. The method sets the 
		 * default folder path to be the user's documents directory. It also 
		 * adjusts the window size and makes it visible.
		 */
		//public function init():void 
		//{
			//folderPath.text=File.userDirectory.nativePath;
			//defaultFolderPath = 
//			stage.nativeWindow.width = Math.min(800, Capabilities.screenResolutionX - 40);
//			stage.nativeWindow.height = Capabilities.screenResolutionY - 40;
//			stage.nativeWindow.visible = true;
			//search();
		//}
			
		/**
		 * Invoked when the user clicks the Search button. This method initiates the search
		 * by building a RegExp pattern based on the searchString text value, and then checking
		 * to see if the specified directory exists. If the directory does not exist, an error
		 * message is displayed; otherwise, the method calls the listDirectoryAsync() method of the
		 * dir object (that points to the directory). The directoryListing event handler processes
		 * the directory contents for this directory.
		 */
		public function search(patternString:String, defaultFolderPath:String):void
		{
			trace("search");
			resultData = new ArrayCollection();
			//var patternString:String = ".mp3";
			patternString = patternString.replace(/\./g, "\\.");
			patternString = patternString.replace(/\*/g, ".*");
			patternString = patternString.replace(/\?/g, ".");
			pattern = new RegExp(patternString, "i");
			var dir:File = new File(defaultFolderPath);
			if (!dir.isDirectory)
			{
				Alert.show("Invalid directory path.", "Error");
			}
			else
			{
				dir.addEventListener(FileListEvent.DIRECTORY_LISTING, dirListed);
				dir.getDirectoryListingAsync();
//				progress.visible = true;
			}
			
		}
		
		/**
		 * Processes the directory contents for this directory, iterating through each node (file or
		 * directory) to see if its name matches the Search pattern. Directories are added to the 
		 * currentSubdirectories array, which is later added to the directoryStack. After examining
		 * all of the nodes, the method then invokes the listDirectoryAsync() method of the next directory
		 * in the directoryStack stack.
		 */	
		private function dirListed(event:FileListEvent):void 
		{
			currentNodes = event.files;
			currentSubdirectories = [];
			nodeCount += currentNodes.length;
			//progress.label = "Files and folders searched: " + nodeCount;
			var node:File;
			var fileExtension:String;
			for (var i:int = 0; i < currentNodes.length; i++) 
			{
				node = currentNodes[i];
				if (node.isDirectory) 
				{
					currentSubdirectories.push(currentNodes[i]);
				}
				if (node.name.search(pattern) > -1) 
				{
					trace("result found");
					var newData:OnzheurSongScan = new OnzheurSongScan(node.name, node.nativePath, node.extension);
					resultData.addItem(newData);
				}
			}
			for (i = currentSubdirectories.length - 1; i > -1; i--) 
			{
				directoryStack.push(currentSubdirectories[i]);
			} 
			var dir:File = directoryStack.pop();
			if (dir == null) {
				trace("search completed");
				//progress.visible = false; // There are no further directories to search. The search is completed.
				dispatchEvent(new OnzheurEvent(OnzheurEvent.END_SEARCH));
			}
			else {
				dir.addEventListener(FileListEvent.DIRECTORY_LISTING, dirListed);
				dir.getDirectoryListingAsync();
			}
		
		}
	}
}
